/**
 * leave
 * ibio-develop
 */
(function(){
var TOTAL_PAGES = 3;
var m_workingHours = true;
var m_lastNavBtn = null;
var m_hTipTimeout = 0;
var m_today = getToday();
var m_bgp = chrome.extension.getBackgroundPage();
var m_data = m_bgp.fetchData();

init();

function init(){
	trace("isTheLatestData", m_bgp.isTheLatestData());
	createNavUI();
	createHistoryUI();
	createConfigUI();
	if(m_bgp.isTheLatestData()){
		trace("m_data", m_data);
		createTodayUI();
		// $("#he-hero").remove();
	}else{
		// $("#he-nav").remove();
		m_bgp.fetchLeaveData();
		createInfoUI();
	}
	checkOffWork();
	changeNav(0);
}

function createNavUI(){
	$("#he-nav").show();
	$("#he-nav>li").children("a").click(onNavClick);
	//default selected
	m_lastNavBtn = $("#he-nav>li:eq(0)");
	m_lastNavBtn.addClass("active");
}

function changeNav(index){
	for(var i = 0; i < TOTAL_PAGES; i++){
		if(i == index){
			$("#he-page-" + i).show();
		}else{
			$("#he-page-" + i).hide();
		}
		}
		$(document).height($("#he-working-care").height());
}

function onNavClick(e){
	if(m_lastNavBtn){
		m_lastNavBtn.removeClass("active");
	}
	$(this).parent().addClass("active");
	m_lastNavBtn = $(this).parent();
	changeNav($(this).parent().index());
}

function createTodayUI(){
	var todayData = m_bgp.findSomedayData(m_today, m_data.leaves);
	var start = new Date(todayData && todayData.first).toTimeString();
	$("#he-today-date").text(todayData.date);
	// $("#he-page-0 h4").text(patchZero(item[0]));
	$("#he-info p").text("第一次刷卡时间:" + patchZero(start.match(/[:\d]+/) && start.match(/[:\d]+/)[0]));
}

function createInfoUI(){
	var todayData = m_bgp.findSomedayData(m_today, m_data.leaves) || {};
	$("#he-today-date").text(todayData.date || m_today);
	$("#he-title").text("获取当日打卡信息失败，请稍后再试。。。").css({color:"red"});
	$("#he-info p").text("第一次刷卡时间:未知");
}

function createHistoryUI(){
	var columns = 7;
	var col = 0;
	var temp = [];
	var i = 0;
	//clone
	var leaves = m_data.leaves ? m_data.leaves.slice(0) : [];
	var firstWeek = new Date(leaves[0] && leaves[0].date).getDay();
	var lastWeek = new Date(leaves[leaves.length - 1] && leaves[leaves.length - 1].date).getDay();
	// trace("firstWeek", firstWeek);
	// trace("lastWeek", lastWeek);
	//
	for(i = 0; i < firstWeek; i++){
		leaves.unshift({});
	}
	//
	for(i = 0; i < (7 - lastWeek - 1); i++){
		leaves.push({});
	}
	//
	_.each(leaves, function(item){
		var delta = new Date(item.end).getTime() - new Date(item.first).getTime();
		var today = new Date().getDate();
		var day = new Date(item.date).getDate();
		var isCurrentDate =  (item.date == m_today);
		var styles = [];
		//0 -- 6
		if(col > 6){col = 0;}
		temp.push(col == 0 ? '<tr>' : '');
		if(day){
			if(delta < (DUTY_HOURS * 60 * 60 * 1000)){
				styles.push("color-crimson");
			}else if(delta > (DUTY_HOURS * 60 * 60 * 1000) && delta < (EXCELLENT_HOURS * 60 * 60 * 1000)){
				styles.push("color-yellow");
			}else{
				styles.push("color-forestgreen");
			}
			//exclude weekends and future days
			if(day >= today || col == 0 || col == 6){
				styles.push("date-vain");	
			}
			temp.push('<td class="' + styles.join(" ") + '">');
			if(isCurrentDate){temp.push("<b>");}
			temp.push(patchZero(day));
			if(isCurrentDate){temp.push("</b>");}
			if(day <= today && delta < (DUTY_HOURS * 60 * 60 * 1000)){
				(col == 0 || col == 6) ? temp.push('<a class="he-a-overtime" date="' + item.date + '">加班</a>') :
													 temp.push('<a class="he-a-ask-day-leave" date="' + item.date + '">请假</a>');
			}
			temp.push('</td>');
		}else{
			temp.push('<td></td>');
		}
		temp.push(col == 6 ? '</tr>' : '');
		col++;
	});
	// trace("temp", temp);
	$("#he-page-1 table tbody").append(temp.join(''));
	
	$(".he-a-ask-day-leave").click(function(e){
		chrome.tabs.create({url:"http://leave.happyelements.net/index.php?controller=application&action=add&day=" + $(e.currentTarget).attr("date")});
	});
	$(".he-a-overtime").click(function(e){
		chrome.tabs.create({url:"http://ot.happyelements.net/?controller=overtime&action=add&day=" + $(e.currentTarget).attr("date")});
	});
	$("#history-learning-more").click(function(e){
		chrome.tabs.create({url:"http://leave.happyelements.net/?controller=access_log&action=index"});
	});
	//
	$("#he-history-year p span").text(new Date().getFullYear() + "年");
	for(var i = 0; i < $("#he-history-month button").length; i++){
		//current month
		if(i == new Date().getMonth()){
			$("#he-history-month button").eq(i).addClass("btn-primary");
		}else{
			$("#he-history-month button").eq(i).addClass("disabled");
		}
	}
}

function createConfigUI(){
	_.each($("#he-page-2").children("button"), function(item){
		$(item).click(onCfgBtnClick);
	});
}

function onCfgBtnClick(e){
	var flag = $(e.currentTarget).attr("flag");
	switch(flag){
		case "btn0":
			m_data.leaves = null;
			break;
		case "btn1":
			m_data.username = null;
			m_data.password = null;
			break;
		case "btn2":
			m_data = {};
			break;
	}
	showTip("清除成功！");
	m_bgp.clearData(m_data);
}

function checkOffWork(){
	//milliseconds
	var pastTime = m_data.pastTime;
	var totalTime = m_data.totalTime;
	var leftTime = m_data.leftTime;
	//decimal
	var percent = Math.floor(pastTime / totalTime * 100);
	if(percent > 100){
		percent = 100;
	}
	// percent = 103;
	$("#he-progress>div:eq(0)").css({width:percent + "%"});
	$("#he-progress>div:eq(1)").css({width:(100 - percent) + "%"});
	$("#he-progress>div:eq(0)").text(getNormalTime(pastTime));
	$("#he-progress>div:eq(1)").text(getNormalTime(leftTime));
	$("#he-info b").text(percent + "%");
	//
	if((pastTime > 0) && (leftTime == 0) && m_workingHours){
		$("#he-title").text("亲爱的，可以下班咯！").css({color:"green"});
		m_workingHours = false;
	}
}

function showTip(txt, time, color){
	// <div id="operation-tip" class="operation-tip"></div>
	var tipNode = $("<div />").attr({id:"operation-tip", "class":"operation-tip"});
	time = (typeof(time) == "undefined") ? 1500 : parseInt(time);
	if(txt){
		$("#operation-tip")[0] ? null : $("#he-page-2").prepend(tipNode);
		$("#operation-tip").html("<span>"+txt+"</span>");
	}else{
		$("#operation-tip").remove();
	}
	if(color){
		$("#operation-tip span").css("color", color);
	}
	clearTimeout(m_hTipTimeout);
	if(time > 0){
		m_hTipTimeout = setTimeout(function(){
			$("#operation-tip").remove();
		}, time);
	}
}

function getNormalTime(timestamp){
	var date = new Date(timestamp);
	return patchZero(date.getUTCHours() + ":" + date.getUTCMinutes());
}

function getNormalHour(timestamp){
	var date = new Date(timestamp);
	return patchZero(date.getUTCHours() + '');
}

function patchZero(input){
	input = String(input) || "";
	// /\d+/g, function($1){return ($1.length <= 2) ?  ("0"+$1) : $1}
	return input.replace(/\d+/g, function($1){
		return ($1.length < 2) ?  ("0" + $1) : $1;
	});
}

}).call(this);